package log

import (
	"gin-web/app/core/config"
	"gin-web/app/utils/env"
	file2 "gin-web/app/utils/file"
	"github.com/sirupsen/logrus"
	"os"
	"sync"
)

var (
	log  *logrus.Entry
	lock sync.RWMutex
)

// 日志输出时间格式模板
const (
	logTimeTpl = "2006-01-02T15:04:05.000Z07:00"
)

func LoadLog(cfg config.Log, prjHome string) *logrus.Entry {

	lock.RLock()
	if log != nil {
		defer lock.RUnlock()
		return log
	}
	lock.RUnlock()
	lock.Lock()
	defer lock.Unlock()

	//二次验证
	if log != nil {
		return log
	}

	var err error
	log, err = instanceLog(cfg, prjHome)
	if err != nil {
		panic(err)
	}

	return log
}

func instanceLog(cfg config.Log, prjHome string) (*logrus.Entry, error) {
	l := logrus.New()

	//输出栈信息
	l.SetReportCaller(true)

	//设置日志level
	switch cfg.Level {
	case "debug":
		l.SetLevel(logrus.DebugLevel)
	case "warn":
		l.SetLevel(logrus.WarnLevel)
	case "error":
		l.SetLevel(logrus.ErrorLevel)
	default:
		l.SetLevel(logrus.InfoLevel)
	}

	//设置日志格式，json or txt
	if cfg.LogFormat == "json" {
		//json
		l.SetFormatter(&logrus.JSONFormatter{
			TimestampFormat: logTimeTpl,
		})
	} else {
		//text
		l.SetFormatter(&logrus.TextFormatter{
			TimestampFormat: logTimeTpl,
		})
	}

	//设置日志输出
	if cfg.Output == "stdout" {
		//输出到控制台
		l.SetOutput(os.Stdout)
	} else {
		//输出到文件
		filePath := cfg.LogPath
		if filePath == "" {
			filePath = "logs/app.log"
		}

		file, err := file2.GetFilePointer(filePath, prjHome)
		if err != nil {
			return nil, err
		}

		l.SetOutput(file)
	}

	//基础字段映射
	logNew := l.WithFields(logrus.Fields{
		"Hostname": env.LocalHostname(),
		"LocalIp":  env.LocalIP(),
	})

	return logNew, nil
}
